package com.easy.util;

import org.apache.commons.codec.digest.DigestUtils;  // 改为这个包

public class DigestUtil {
    private final static int saltIndex =0;
    private final static int countIndex = 12;
    private final static char[] items = {'0','1','2','3','4',
            '5','6', '7','8','9','a','b','c','d','e','f'};
    public static String randomDigest(String pass){
        int randomCountIndex = (int) (Math.random() *items.length);
        int randomSaltIndex = (int) (Math.random() *items.length);

        char count = items[randomCountIndex];
//        System.out.println(count);
        char salt = items[randomSaltIndex];
//        System.out.println(salt);



        String result = pass+salt;

        for(int i=0; i<count; i++){
            // 加密
            result = DigestUtils.md5Hex(result);
        }
//        result 就是加密之后的字符串
        result = result.substring(0,saltIndex)+salt+
                result.substring(saltIndex);
//        System.out.println(result);
        result = result.substring(0,countIndex)+count+
                result.substring(countIndex);
//        System.out.println(result);
        return result;
    }

    //  比较密文
    public static boolean decode(String password,String digestPassword){
        if (password == null || digestPassword == null || digestPassword.length() < countIndex + 1) {
            return false;
        }

        char salt = digestPassword.charAt(saltIndex);
        char count = digestPassword.charAt(countIndex);

        int countChar;
        // 确保 countChar 是有效数字
        try {
            countChar = Character.getNumericValue(count);
            if (countChar < 0) {
                return false;
            }
        } catch (NumberFormatException e) {
            return false;
        }

        //  开始加密
        String result = password + salt;

        for (int i = 0;i<count; i++){
            result = DigestUtils.md5Hex(result);
        }
        result = result.substring(0,saltIndex)+salt+
                result.substring(saltIndex);
        result = result.substring(0,countIndex)+count+
                result.substring(countIndex);
        return result.equals(digestPassword);
    }
//    public static void main(String[] args) {
//        randomDigest("123123");
//        boolean bool = decode("123123","a5a7031e349c02aa0150b450e39f71faeb");
//        System.out.println(bool);
//    }
public static void main(String[] args) {
    String password = "123123";
    String digest = randomDigest(password);
    System.out.println("Generated Digest: " + digest);

    boolean bool = decode(password, "d18116512970ab22672a65bd6e7cd97188");
    System.out.println("Password matches: " + bool);
}

}
